package com.example.mediamoudle.mediacodec

import android.content.Context
import android.graphics.SurfaceTexture
import android.opengl.GLES11Ext
import android.opengl.GLES20
import android.opengl.GLES30
import android.opengl.GLES30.glBindVertexArray
import android.opengl.GLSurfaceView
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class CustomGLSurfaceView (context: Context,attributeSet: AttributeSet?=null):GLSurfaceView(context,attributeSet),GLSurfaceView.Renderer{
    init {
        setEGLContextClientVersion(2)
        setRenderer(this)
        renderMode = RENDERMODE_WHEN_DIRTY
        preserveEGLContextOnPause = false
        cameraDistance = 100f

    }

    private var surfaceTexture: SurfaceTexture? = null
    private var textureId = 0
    private lateinit var surfaceView:Surface

    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        var texture=IntArray(1)
        GLES20.glGenTextures(1,texture,0);
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES ,texture[0]);
        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
            GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR.toFloat()
        );



      //  GLES20.glGenTextures(1,texture ,0)
        textureId = texture[0]
        surfaceTexture = SurfaceTexture(textureId)
        surfaceTexture?.setOnFrameAvailableListener {
            requestRender()
        }
         surfaceView = Surface(surfaceTexture)


    }
    fun getSurface():Surface = surfaceView
    private val fFrame = IntArray(1)
    private val fTexture = IntArray(1)
    private var viewWidth = 0
    private var viewHeight = 0
    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        viewWidth=width;
        viewHeight=height;
        GLES20.glViewport(0, 0, width, height)

        GLES20.glDeleteFramebuffers(1, fFrame, 0);
        GLES20.glDeleteTextures(1, fTexture, 0);

        GLES20.glGenFramebuffers(1,fFrame,0);
        EasyGlUtils.genTexturesWithParameter(1,fTexture,0, GLES20.GL_RGBA,width,height);
   }

    override fun onDrawFrame(gl: GL10) {
      //  surfaceTexture?.updateTexImage()
        Log.i("TAGafsd", "onDrawFrame: 绘制")

      /*  EasyGlUtils.bindFrameTexture(fFrame[0],fTexture[0]);
        GLES20.glViewport(0,0,viewWidth,viewHeight);
        EasyGlUtils.unBindFrameBuffer();
        GLES20.glViewport(0,0,viewWidth,viewHeight);*/
      /*  GLES20.glClear(GLES30.GL_COLOR_BUFFER_BIT)
        surfaceTexture?.updateTexImage()
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, fTexture[0])
        //GLES20.glBindVertexArray(fFrame[0])
        GLES20.glDrawElements(GLES30.GL_TRIANGLE_STRIP, 6, GLES30.GL_UNSIGNED_INT, 0)

*/
    }
}